<?php

/**
 * sales actions.
 *
 * @package    Porba
 * @subpackage sales
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class salesActions extends sfActions {

    public function executeIndexContacts(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'contacts';
        $this->showIndicator = 'index';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);

        //Use index template for this action
        $this->setTemplate('index');
    }

    public function executeIndexOrders(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'orders';
        $this->showIndicator = 'index';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);
        
        if(isset($_SESSION['page'])){
            unset($_SESSION['page']);
            unset($_SESSION['price']);
        }
        
        //Use index template for this action
        $this->setTemplate('index');
    }

    public function executeIndexPnp(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'pnp';
        $this->showIndicator = 'index';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);
      
        //Unset all the sessions that are used in functions of materials&products
        if(isset($_SESSION['partlist'])){
            unset($_SESSION['partlist']);
        }   
        if(isset($_SESSION['pageProduct'])){
            unset($_SESSION['pageProduct']);
        }       
        if(isset($_SESSION['page'])){
            unset($_SESSION['page']);
        }
        
        //Use index template for this action
        $this->setTemplate('index');
    }

    public function executeShowContact(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'contacts';
        $this->showIndicator = 'showContact';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);

        //Contact
        $this->contact = $this->getRoute()->getObject();
        $this->forward404Unless($this->contact);
 
        //Use index template for this action
        $this->setTemplate('index');
    }

    public function executeShowOrder(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'orders';
        $this->showIndicator = 'showOrder';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);
     
        //Order
        $this->order = $this->getRoute()->getObject();
        $this->forward404Unless($this->order);

        //Pager with all the items of this order
        $this->pagerItems = new sfDoctrinePager('PP', sfConfig::get('app_max_orders_contact_on_page'));
        $this->pagerItems->setQuery(PPView::findbyOrderQuery($this->order));
        $this->pagerItems->setPage($request->getParameter('pageorderinfo', 1));
        $this->pagerItems->init();

        //Use index template for this action
        $this->setTemplate('index');
    }
    
    public function executeShowMaterialsOrder(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'orders';
        $this->showIndicator = 'showMaterialsOrder';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);
        
        //Order
        $this->order = $this->getRoute()->getObject();
        $this->forward404Unless($this->order);

        //Pager with all the materials used for this order
        $this->pagerMaterials = new sfDoctrinePager('MaterialsUsed', sfConfig::get('app_max_orders_contact_on_page'));
        $this->pagerMaterials->setQuery(MaterialsUsedView::findbyOrderQuery($this->order));
        $this->pagerMaterials->setPage($request->getParameter('page', 1));
        $this->pagerMaterials->init();
        
        //Use index template for this action
        $this->setTemplate('index');
    }

    public function executeShowOrdersContact(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'contacts';
        $this->showIndicator = 'showOrdersContact';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);

        //Contact orders
        $this->contact = $this->getRoute()->getObject();
        $this->pagerOrdersContact = new sfDoctrinePager('_Order', sfConfig::get('app_max_orders_contact_on_page'));
        $this->pagerOrdersContact->setQuery(_OrderTable::getInstance()->findByContact($this->contact));
        $this->pagerOrdersContact->setPage($request->getParameter('pageorderscontact', 1));
        $this->pagerOrdersContact->init();

        $this->forward404Unless($this->contact);

        //Use index template for this action
        $this->setTemplate('index');
    }

    public function executeShowNoteContact(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'contacts';
        $this->showIndicator = 'showNote';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);

        //Contact
        $this->contact = $this->getRoute()->getObject();

        //Use index template for this action
        $this->setTemplate('index');
    }
    
    public function executeShowPriceList(sfWebRequest $request) {
        $this->setLayout(false);
        
        //Create a date that is the current date
        $date = getdate();
        $day = $date['mday'];
        $month = $date['mon'];
        $year = $date['year'];
        $this->today = $day.'-'.$month.'-'.$year;
           
        $this->version = 'showPriceList';
        $this->setTemplate('show');
    }  

    public function executeNewContact(sfWebRequest $request) {
        $this->tab = 'contacts';
        $this->form = new ContactForm();

        //Use new template for this action
        $this->setTemplate('new');
    }

    public function executeNewOrder(sfWebRequest $request) {
        $this->tab = 'orders';
        $this->form = new _OrderForm();        
        $this->parts = PartTable::findAllWithPrice();
        $this->products = ProductTable::findAllOrderByName();
  
        //Use new template for this action
        $this->setTemplate('new');
    }
    
    public function executeStockOrder(sfWebRequest $request) {
        $this->tab = 'stock';
        $this->form = new _OrderForm();       
        $this->products = ProductTable::findAllOrderByName();
  
        //Use new template for this action
        $this->setTemplate('new');
    }    

    public function executeReturnOrder(sfWebRequest $request) {
        $this->tab = 'return';
        $this->form = new _OrderForm();
  
        //Use new template for this action
        $this->setTemplate('new');
    }

    public function executeNewProduct(sfWebRequest $request) {
        $this->tab = 'products';
        $this->form = new ProductForm();
        $this->parts = PartTable::getInstance()->findAll();

        //Use new template for this action
        $this->setTemplate('new');
    }

    public function executeNewPart(sfWebRequest $request) {
        $this->tab = 'parts';
        $this->form = new PartForm();

        //Use new template for this action
        $this->setTemplate('new');
    }

    public function executeCreateContact(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->tab = 'contacts';
        $this->form = new ContactForm();

        $this->processFormContact($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeCreateOrder(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->tab = 'orders';
        $this->form = new _OrderForm();
 
        $this->processFormOrder($request, $this->form);

        $this->parts = PartTable::findAllWithPrice();        
        $this->products = ProductTable::findAllOrderByName();

        $this->setTemplate('new');
    }
    
    public function executeCreateStockOrder(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $this->tab = 'stock';
        $this->form = new _OrderForm();
 
        $this->processFormStockOrder($request, $this->form);
      
        $this->products = ProductTable::findAllOrderByName();

        $this->setTemplate('new');
    }
    
    public function executeCreatePriceList(sfWebRequest $request) {
        $this->parts = PartTable::findAllWithPrice();        
        $this->products = ProductTable::findAllOrderByName();
        $this->tab = 'priceList';
 
        $this->setTemplate('new');
    }
    
    public function executeCreateReturnOrder(sfWebRequest $request) {
        $this->forward404Unless($order_no_query = _OrderTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'return';
        $this->form = new _OrderForm();       
        $total = $_POST['totalprice'];
        
        //Set current date
        $date = getdate();
        $day = $date['mday'];
        $month = $date['mon'];
        $year = $date['year'];
        $today = $year.'-'.$month.'-'.$day;
        
        //Create a new return order and assign all the variables of the selected order to this new order
        $order_new = new _Order();
        $order_new->setContactId($order_no_query->getContactId());
        $order_new->setCOrderNumber($order_no_query->getCOrderNumber());
        $order_new->setShipLastname($order_no_query->getShipLastname());
        $order_new->setDateRecieved($today);
        $order_new->setDateCompleted($today);
        $order_new->setShipFirstname($order_no_query->getShipFirstname());
        $order_new->setShipAddress($order_no_query->getShipAddress());
        $order_new->setShipZipcode($order_no_query->getShipZipcode());
        $order_new->setShipCity($order_no_query->getShipCity());
        $order_new->setShipCountry($order_no_query->getShipCountry());
        $order_new->setCategoryName('return order');
        $order_new->setStatus('collected');
        $order_new->setTotalPrice($total);
                
        $this->processFormReturnOrder($request, $this->form, $order_new);

        $this->setTemplate('new');
    }

    public function executeCreateProduct(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));
        $this->tab = 'products';
        $this->form = new ProductForm();
        $this->parts = PartTable::getInstance()->findAll();

        $this->processFormProduct($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeCreatePart(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST));
        $this->tab = 'parts';
        $this->form = new PartForm();

        $this->processFormPart($request, $this->form);

        $this->setTemplate('new');
    }

    public function executeEditContact(sfWebRequest $request) {
        $this->forward404Unless($contact = ContactTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object contact does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'contacts';
        $this->form = new ContactForm($contact);

        $this->setTemplate('edit');
    }

    public function executeEditOrder(sfWebRequest $request) {
        $this->forward404Unless($order = _OrderTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'orders';
        $this->form = new _OrderForm($order);
        $this->status = $order->getStatus();
        $this->products= ProductTable::getInstance()->findAll();
        $this->parts = PartTable::getInstance()->findAll();  
        
        $this->setTemplate('edit');
    }
    
    public function executeEditStockOrder(sfWebRequest $request) {
        $this->forward404Unless($order = _OrderTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'stock';
        $this->form = new _OrderForm($order);
        $this->status = $order->getStatus();
        $this->products= ProductTable::getInstance()->findAll(); 
        
        $this->setTemplate('edit');
    }
    
    public function executeEditReturnOrder(sfWebRequest $request) {
        $this->forward404Unless($order = _OrderTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'return';
        $this->form = new _OrderForm($order);
        
        $this->setTemplate('edit');
    }

    public function executeEditProduct(sfWebRequest $request) {
        $this->forward404Unless($product = ProductTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object product does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'products';
        $this->form = new ProductForm($product);
        $this->parts = PartTable::getInstance()->findAll();

        $this->setTemplate('edit');
    }

    public function executeEditPart(sfWebRequest $request) {
        $this->forward404Unless($part = PartTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object part does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'parts';
        $this->form = new PartForm($part);

        $this->setTemplate('edit');
    }

    public function executeUpdateContact(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($contact = ContactTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object contact does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'contacts';
        $this->form = new ContactForm($contact);

        $this->processFormContactEdit($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeUpdateOrder(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($order = _OrderTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'orders';
        $this->products= ProductTable::getInstance()->findAll();
        $this->parts = PartTable::getInstance()->findAll(); 
        $this->form = new _OrderForm($order);

        $this->processFormOrderEdit($request, $this->form);

        $this->setTemplate('edit');
    }
    
    public function executeUpdateStockOrder(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($order = _OrderTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'stock';
        $this->products= ProductTable::getInstance()->findAll(); 
        $this->form = new _OrderForm($order);

        $this->processFormStockOrderEdit($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeUpdateProduct(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($product = ProductTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object product does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'products';
        $this->form = new ProductForm($product);

        $this->processFormProductEdit($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeUpdatePart(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($part = PartTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object part does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'parts';
        $this->form = new PartForm($part);

        $this->processFormPartEdit($request, $this->form);

        $this->setTemplate('edit');
    }

    public function executeDeleteContact(sfWebRequest $request) {
        $request->checkCSRFProtection();
        
        $this->forward404Unless($contact = ContactTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object contact does not exist (%s).', $request->getParameter('id')));
        $contact->delete();

        $this->tab = 'contacts';
        $this->redirect('sales/indexContacts');
    }

    public function executeDeleteOrder(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->forward404Unless($order = _OrderTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $order->delete();

        $this->tab = 'orders';
        $this->redirect('sales/indexOrders');
    }

    public function executeDeleteProduct(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->forward404Unless($product = ProductTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object product does not exist (%s).', $request->getParameter('id')));
        $product->delete();

        $this->tab = 'products';
        $this->redirect('sales/indexPnp');
    }

    public function executeDeletePart(sfWebRequest $request) {
        $request->checkCSRFProtection();

        $this->forward404Unless($part = PartTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object part does not exist (%s).', $request->getParameter('id')));
        $part->delete();

        $this->tab = 'parts';
        $this->redirect('sales/indexPnp');
    }

    protected function processFormContact(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $contact = $form->save();

            $this->redirect('sales_index_contacts');
        }
    }
    
    protected function processFormContactEdit(sfWebRequest $request, sfForm $form){
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $contact = $form->save();

            $this->redirect('sales_index_contacts');
        }
    }

    /**
     * Save the customer order and add an orderline
     * If the status is set to 'in production' modify the stock of the products and materials belonging to this order
     * @param sfWebRequest $request
     * @param sfForm $form 
     */
    protected function processFormOrder(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $order = $form->save();
                     
            if (isset($_SESSION['orderlist'])){
                foreach($_SESSION['orderlist'] as $session){  
                    $orderline = new Orderline();
                    $amount = $session['amount'];
                    $orderline->setAmount($amount);
                    $id = $session['id'];
                    $cat = $session['cat'];
                    if($cat == 'Product'){
                        $orderline->setProductId($id);
                    }
                    if($cat == 'Material'){
                        $orderline->setMaterialId($id);
                    }
                    $discount = $session['discount'];
                    $orderline->setDiscount($discount);
                    $price = $session['price'];
                    $orderline->setPrice($price);
                    $orderline->setOrderId($order->getId());
                    $orderline->save();

                    //Check if the status is 'in production' and not 'quotation'
                    if($order->getStatus() == 'in production'){
                    
                        //Modify the stock accordingly
                        if($cat == 'Product'){
                            $product = ProductTable::getInstance()->findOneBy('id', $id);
                            $stockProduct = $product->getStock();
                            if($stockProduct >= $amount){ //there are enough products in stock
                                $newStock = $product->getStock() - $amount;
                                $newReserved = $product->getReserved() + $amount;
                                $product->setStock($newStock);
                                $product->setReserved($newReserved);
                                $product->save();

                                //Add a reservedline to the database
                                $this->createReservedLine('product', $order->getId(), $product->getId(), $amount, $amount);                       
                            }
                            else{ //not enough products in stock, new ones have to be produced
                                $product->setStock(0);
                                $product->setReserved($product->getReserved() + $stockProduct);
                                $product->save();
                                $amountToProduce = $amount - $stockProduct;

                                //Add a reservedline to the database
                                $this->createReservedLine('product', $order->getId(), $product->getId(), $amount, $amount);                       

                                //check what parts belong to this product and subtract the parts from stock
                                $parts = ProductlineTable::getInstance()->findBy('product_id', $product->getId());

                                foreach($parts as $productline){
                                    $part = PartTable::getInstance()->findOneBy('id', $productline->getPartId());
                                    $amount = $productline->getAmount();
                                    $stock = $part->getStock() - ($amount * $amountToProduce);
                                    $reserved = $part->getReserved() + ($amount * $amountToProduce);
                                    $part->setStock($stock);
                                    $part->setReserved($reserved);
                                    $part->save();                                                       

                                    $reservedlines = ReservedlineTable::getInstance()->findBy('order_id', $order->getId());
                                    if($reservedlines->count() == 0){ //No materials have been added to the order yet
                                        //Add a reservedline to the database
                                        $this->createReservedLine('material', $order->getId(), $part->getId(), ($amount * $amountToProduce), ($amount * $amountToProduce));                             
                                    }
                                    else{ //check if the material has already been added to the order in reservedline table
                                        $inlist = false;
                                        foreach($reservedlines as $line){
                                            if($part->getId() == $line->getMaterialId()){ 
                                                $inlist = true;
                                                break;
                                            }
                                        }
                                        if($inlist == true){ //if the material already is in the table, update the amount reserved  and required for that material
                                                $newAmount = $line->getRequired() + ($amount * $amountToProduce);
                                                ReservedlineTable::setReserved($part->getId(), $order->getId(), $newAmount);  
                                                ReservedlineTable::setRequired($part->getId(), $order->getId(), $newAmount);
                                        }
                                        else{ //if the material has not been added yet, add a new line
                                            //Add a reservedline to the database
                                            $this->createReservedLine('material', $order->getId(), $part->getId(), ($amount * $amountToProduce), ($amount * $amountToProduce));  
                                        }                          
                                    }
                                }
                            }
                        }
                        if($cat == 'Material'){
                            $part = PartTable::getInstance()->findOneBy('id', $id);
                            $stock = $part->getStock() - ($amount);
                            $reserved = $part->getReserved() + ($amount);
                            $part->setStock($stock);
                            $part->setReserved($reserved);
                            $part->save();                                                       

                            $reservedlines = ReservedlineTable::getInstance()->findBy('order_id', $order->getId());
                            if($reservedlines->count() == 0){ //No materials have been added to the order yet
                                //Add a reservedline to the database
                                $this->createReservedLine('material', $order->getId(), $part->getId(), $amount, $amount);                             
                            }
                            else{ //check if the material has already been added to the order in reservedline table
                                $inlist = false;
                                foreach($reservedlines as $line){
                                    if($part->getId() == $line->getMaterialId()){ 
                                        $inlist = true;
                                        break;
                                    }
                                }
                                if($inlist == true){ //if the material already is in the table, update the amount reserved  and required for that material
                                    $newAmount = $line->getRequired() + ($amount);
                                    ReservedlineTable::setReserved($part->getId(), $order->getId(), $newAmount);  
                                    ReservedlineTable::setRequired($part->getId(), $order->getId(), $newAmount);
                                }
                                else{ //if the material has not been added yet, add a new line
                                    //Add a reservedline to the database
                                    $this->createReservedLine('material', $order->getId(), $part->getId(), $amount, $amount); 
                                }                          
                             }
                          }
                    }
                } 
            }
            unset($_SESSION['orderlist']);
            unset($_SESSION['page']);
            unset($_SESSION['price']);
            
            $this->redirect('sales_index_orders');
        }
    }
    
   /**
    * Save the stock order, add an orderline and modify the stock
    * @param sfWebRequest $request
    * @param sfForm $form 
    */  
    protected function processFormStockOrder(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $order = $form->save();
                     
            if (isset($_SESSION['stockOrderlist'])){
                foreach($_SESSION['stockOrderlist'] as $session){  
                    $orderline = new Orderline();
                    $amount = $session['amount'];
                    $orderline->setAmount($amount);
                    $id = $session['id'];
                    $orderline->setProductId($id);
                    $discount = $session['discount'];
                    $orderline->setDiscount($discount);
                    $price = $session['price'];
                    $orderline->setPrice($price);
                    $orderline->setOrderId($order->getId());
                    $orderline->save();
                    
                    //Modify the stock accordingly
                    $product = ProductTable::getInstance()->findOneBy('id', $id);
                    $amountToProduce = $amount;

                    //Add a reservedline to the database
                    $this->createReservedLine('product', $order->getId(), $product->getId(), 0, $amount);                                   

                    //check what parts belong to this product and subtract the parts from stock
                    $parts = ProductlineTable::getInstance()->findBy('product_id', $product->getId());
                    foreach($parts as $productline){
                        $part = PartTable::getInstance()->findOneBy('id', $productline->getPartId());
                        $amount = $productline->getAmount();
                        $stock = $part->getStock() - ($amount * $amountToProduce);
                        $reserved = $part->getReserved() + ($amount * $amountToProduce);
                        $part->setStock($stock);
                        $part->setReserved($reserved);
                        $part->save();                                                       

                        $reservedlines = ReservedlineTable::getInstance()->findBy('order_id', $order->getId());
                        $inlist = false;
                        foreach($reservedlines as $line){
                            if($part->getId() == $line->getMaterialId()){ 
                                $inlist = true;
                                break;
                            }
                        }
                        if($inlist == true){ //if the material already is in the table, update the amount reserved  and required for that material
                            $newAmount = $line->getRequired() + ($amount * $amountToProduce);
                            ReservedlineTable::setReserved($part->getId(), $order->getId(), $newAmount);  
                            ReservedlineTable::setRequired($part->getId(), $order->getId(), $newAmount);
                        }
                        else{ //if the material has not been added yet, add a new line
                            //Add a reservedline to the database
                            $this->createReservedLine('material', $order->getId(), $part->getId(), ($amount * $amountToProduce), ($amount * $amountToProduce)); 
                        }                          
                    }
                } 
            }
            unset($_SESSION['stockOrderlist']);
            
            $this->redirect('sales_index_orders');
        }
    }
    
    /**
     * Save the given return order, add an orderline and add all the returned items to the stock
     * @param sfWebRequest $request
     * @param sfForm $form
     * @param _Order $ordernew 
     */
    protected function processFormReturnOrder(sfWebRequest $request, sfForm $form, _Order $ordernew) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));     
           $ordernew->save();  
           
           if (isset($_SESSION['return_list'])){
                foreach($_SESSION['return_list'] as $session){  
                    $orderline = new Orderline();
                    $amount = $session['return'];
                    $orderline->setAmount($amount);
                    $id = $session['id'];
                    $cat = $session['cat'];
                        
                    if($cat == 'Product'){
                        $orderline->setProductId($id);

                        //add amount to stock
                        $product = ProductTable::getInstance()->findOneBy('id', $id);
                        $stock = $product->getStock() + $amount;
                        $product->setStock($stock);
                        $product->save();                            
                    }
                    if($cat == 'Material'){
                        $orderline->setMaterialId($id);
                        
                        //add amount to stock
                        $part = PartTable::getInstance()->findOneBy('id', $id);
                        $stock = $part->getStock() + $amount;
                        $part->setStock($stock);
                        $part->save(); 
                        
                        //add history line
                        $historyLine = new MaterialHistory();
                        $historyLine->setMaterialId($part->getId());
                        $historyLine->setSold(-$amount);
                        $historyLine->setStock($stock);
                        $historyLine->save();
                    }
                    
                    $discount  = $session['discount'];
                    $orderline->setDiscount($discount);
                    $price = $session['price'];
                    $orderline->setPrice($price);
                    $orderline->setOrderId($ordernew->getId());
                    $orderline->save();
                } 
           }
           unset($_SESSION['return_list']);
           
           $this->redirect('sales_index_orders');
    }
    
    /**
     * Save the customer order and modify the stock according to the status change
     * @param sfWebRequest $request
     * @param sfForm $form 
     */
    protected function processFormOrderEdit(sfWebRequest $request, sfForm $form){
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $oldstatus = $form->getObject()->getStatus();
            $order = $form->save();

            //Status changes from 'quotation' to 'in production'
            if($oldstatus == 'quotation' && $order->getStatus() == 'in production'){
                //Get the orderlines of this order
                $orderlines = OrderlineTable::getInstance()->findBy('order_id', $order->getId());
                
                foreach($orderlines as $line){
                        $amount = $line->getAmount();
                        //Modify the stock accordingly
                        if($line->getProductId() != null){
                            $product = ProductTable::getInstance()->findOneBy('id', $line->getProductId());
                            $stockProduct = $product->getStock();
                            if($stockProduct >= $amount){ //there are enough products in stock
                                $newStock = $product->getStock() - $amount;
                                $newReserved = $product->getReserved() + $amount;
                                $product->setStock($newStock);
                                $product->setReserved($newReserved);
                                $product->save();

                                //Add a reservedline to the database
                                $this->createReservedLine('product', $order->getId(), $product->getId(), $amount, $amount);                       
                            }
                            else{ //not enough products in stock, new ones have to be produced
                                $product->setStock(0);
                                $product->setReserved($product->getReserved() + $stockProduct);
                                $product->save();
                                $amountToProduce = $amount - $stockProduct;

                                //Add a reservedline to the database
                                $this->createReservedLine('product', $order->getId(), $product->getId(), $stockProduct, $amount);                        

                                //check what parts belong to this product and subtract the parts from stock
                                $parts = ProductlineTable::getInstance()->findBy('product_id', $product->getId());
                                foreach($parts as $productline){
                                    $part = PartTable::getInstance()->findOneBy('id', $productline->getPartId());
                                    $amount = $productline->getAmount();
                                    $stock = $part->getStock() - ($amount * $amountToProduce);
                                    $reserved = $part->getReserved() + ($amount * $amountToProduce);
                                    $part->setStock($stock);
                                    $part->setReserved($reserved);
                                    $part->save();                                                       

                                    $reservedlines = ReservedlineTable::getInstance()->findBy('order_id', $order->getId());
                                    if($reservedlines->count() == 0){ //No materials have been added to the order yet
                                        //Add a reservedline to the database
                                        $this->createReservedLine('material', $order->getId(), $part->getId(), ($amount * $amountToProduce), ($amount * $amountToProduce));                             
                                    }
                                    else{ //check if the material has already been added to the order in reservedline table
                                        $inlist = false;
                                        foreach($reservedlines as $line){
                                            if($part->getId() == $line->getMaterialId()){ 
                                                $inlist = true;
                                                break;
                                            }
                                        }
                                        if($inlist == true){ //if the material already is in the table, update the amount reserved  and required for that material
                                                $newAmount = $line->getRequired() + ($amount * $amountToProduce);
                                                ReservedlineTable::setReserved($part->getId(), $order->getId(), $newAmount);  
                                                ReservedlineTable::setRequired($part->getId(), $order->getId(), $newAmount);
                                        }
                                        else{ //if the material has not been added yet, add a new line
                                            //Add a reservedline to the database
                                            $this->createReservedLine('material', $order->getId(), $part->getId(), ($amount * $amountToProduce), ($amount * $amountToProduce));
                                        }                          
                                    }
                                }
                            }
                        }
                        if($line->getMaterialId() != null){
                            $part = PartTable::getInstance()->findOneBy('id', $line->getMaterialId());
                            $stock = $part->getStock() - ($amount);
                            $reserved = $part->getReserved() + ($amount);
                            $part->setStock($stock);
                            $part->setReserved($reserved);
                            $part->save();                                                       

                            $reservedlines = ReservedlineTable::getInstance()->findBy('order_id', $order->getId());
                            if($reservedlines->count() == 0){ //No materials have been added to the order yet
                                //Add a reservedline to the database
                                $this->createReservedLine('material', $order->getId(), $part->getId(), $amount, $amount);                             
                            }
                            else{ //check if the material has already been added to the order in reservedline table
                                $inlist = false;
                                foreach($reservedlines as $line){
                                    if($part->getId() == $line->getMaterialId()){ 
                                        $inlist = true;
                                        break;
                                    }
                                }
                                if($inlist == true){ //if the material already is in the table, update the amount reserved  and required for that material
                                    $newAmount = $line->getRequired() + ($amount);
                                    ReservedlineTable::setReserved($part->getId(), $order->getId(), $newAmount);  
                                    ReservedlineTable::setRequired($part->getId(), $order->getId(), $newAmount);
                                }
                                else{ //if the material has not been added yet, add a new line
                                    //Add a reservedline to the database
                                    $this->createReservedLine('material', $order->getId(), $part->getId(), $amount, $amount); 
                                }                          
                             }
                         }
                }
            }   
            //Status changes from 'in production' to 'ready'
            if($order->getStatus() == 'ready' && $order->getDateReady() == null){
                //Get reservedlines belonging to this order
                $reservedlines = ReservedlineTable::getInstance()->findBy('order_id', $order->getId());               
                foreach($reservedlines as $line){
                    //check if the line refers to a material
                    if($line->getMaterialId() != null){
                        //Get the amount in production and reserved of each line and the material
                        $production = $line->getProduction();
                        $reserved = $line->getReserved();
                        $material = PartTable::getInstance()->findOneBy('id', $line->getMaterialId());
                        
                        //Get the orderlines of this order
                        $orderlines = OrderlineTable::getInstance()->findBy('order_id', $order->getId());
                        //Check to see if the material occurs in the orderlines
                        $isSold = false;
                        foreach($orderlines as $orderline){
                            if($orderline->getMaterialId() == $material->getId()){
                                $isSold = true;
                                break;
                            }
                        }
                        if($isSold){ //material is sold seperate
                            $amountToSell = $orderline->getAmount();
                            //Subtract the production and reserved amounts from the material
                            $material->setInProduction($material->getInProduction() - $production);
                            $material->setReserved($material->getReserved() - ($reserved - $amountToSell));
                            $material->setStock($material->getStock() + ($reserved - $amountToSell));
                            //save the material
                            $material->save();                            
                        }
                                             
                        if(!$isSold){ //material is only used to make product
                            //Subtract the production and reserved amounts from the material
                            $material->setInProduction($material->getInProduction() - $production);
                            $material->setReserved($material->getReserved() - $reserved);
                            $material->setStock($material->getStock() + $reserved);
                            //save the material
                            $material->save();
                        }
                    }
                    else{
                        //Get the reserved and required amount and the product
                        $required = $line->getRequired();
                        $reserved = $line->getReserved();
                        $product = ProductTable::getInstance()->findOneBy('id', $line->getProductId());
                        //Add the amount that had to be produced for the order to the reserved amount of the product
                        $amountProduced = $required - $reserved;
                        $product->setReserved($product->getReserved() + $amountProduced);
                        //save the product
                        $product->save();
                        //Add a line to the history of the product if new ones have been produced
                        if($amountProduced != 0){
                            $historyLine = new ProductHistory();
                            $historyLine->setProductId($product->getId());
                            $historyLine->setProduced($amountProduced);
                            $historyLine->setOrderId($order->getId());
                            $historyLine->setStock($product->getStock() + $product->getReserved());
                            $historyLine->save();
                        }
                    }                   
                }
                //set current date for date rdy order and save order
                $date = getdate();
                $day = $date['mday'];
                $month = $date['mon'];
                $year = $date['year'];
                $today = $year.'-'.$month.'-'.$day;

                $order->setDateReady($today);
                $order->save();
            }
            //Status changes from 'ready' to 'collected'
            if($oldstatus == 'ready' && $order->getStatus() == 'collected'){
                //Get reservedlines belonging to this order
                $reservedlines = ReservedlineTable::getInstance()->findBy('order_id', $order->getId());               
                foreach($reservedlines as $line){ 
                    //check if the line refers to a product
                    if($line->getProductId() != null){
                        //get the amount required for this order and the product
                        $required = $line->getRequired();
                        $product = ProductTable::getInstance()->findOneBy('id', $line->getProductId());   
                        //subtract the amount required for the order from the amount reserved of product
                        $product->setReserved($product->getReserved() - $required);
                        //save the product
                        $product->save();
                        //Add a line to the product history
                        $historyLine = new ProductHistory();
                        $historyLine->setProductId($product->getId());
                        $historyLine->setSold($required);
                        $historyLine->setOrderId($order->getId());
                        $historyLine->setStock($product->getStock() + $product->getReserved());
                        $historyLine->save();
                    }else{
                        //Get the orderlines of this order
                        $orderlines = OrderlineTable::getInstance()->findBy('order_id', $order->getId());
                        $material = PartTable::getInstance()->findOneBy('id', $line->getMaterialId());
                        //Check to see if the material occurs in the orderlines
                        $isSold = false;
                        foreach($orderlines as $orderline){
                            if($orderline->getMaterialId() == $material->getId()){
                                $isSold = true;
                                break;
                            }
                        }
                        if($isSold){ //material is sold seperate
                            $amountToSell = $orderline->getAmount();
                            //Subtract the amount to be sold from the amount reserved of material
                            $material->setReserved($material->getReserved() - $amountToSell);
                            //save the material
                            $material->save();   
                            //Add history line to material
                            $historyLine = new MaterialHistory();
                            $historyLine->setMaterialId($material->getId());
                            $historyLine->setSold($amountToSell);
                            $historyLine->setStock($material->getStock());
                            $historyLine->save();
                        }                        
                    }
                }               
                
                //Set current date
                $date = getdate();
                $day = $date['mday'];
                $month = $date['mon'];
                $year = $date['year'];
                $today = $year.'-'.$month.'-'.$day;
                
                $order->setDateCompleted($today);
                $order->save();
            }
            unset($_SESSION['page']);
            unset($_SESSION['price']);
            $this->redirect('sales_index_orders');
        }
    }

    /**
     * Save the stock order and modify the stock if the status changes from 'in production' to 'ready'
     * @param sfWebRequest $request
     * @param sfForm $form 
     */
    protected function processFormStockOrderEdit(sfWebRequest $request, sfForm $form){
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $oldstatus = $form->getObject()->getStatus();
            $order = $form->save();
            
            if($order->getStatus() == 'ready' && $oldstatus == 'in production'){
                //Get reservedlines belonging to this order
                $reservedlines = ReservedlineTable::getInstance()->findBy('order_id', $order->getId());               
                foreach($reservedlines as $line){
                    //check if the line refers to a material
                    if($line->getMaterialId() != null){
                        //Get the amount in production and reserved of each line and the material
                        $production = $line->getProduction();
                        $reserved = $line->getReserved();
                        $material = PartTable::getInstance()->findOneBy('id', $line->getMaterialId());
                        
                        //Subtract the production and reserved amounts from the material
                        $material->setInProduction($material->getInProduction() - $production);
                        $material->setReserved($material->getReserved() - $reserved);
                        $material->setStock($material->getStock() + $reserved);
                        //save the material
                        $material->save();                     
                    }
                    else{
                        //Get the reserved and required amount and the product
                        $required = $line->getRequired();
                        $product = ProductTable::getInstance()->findOneBy('id', $line->getProductId());
                        //Add the amount that had to be produced for the order to the stock of the product
                        $product->setStock($product->getStock() + $required);
                        //save the product
                        $product->save();
                        //Add a line to the history of the product
                        $historyLine = new ProductHistory();
                        $historyLine->setProductId($product->getId());
                        $historyLine->setProduced($required);
                        $historyLine->setOrderId($order->getId());
                        $historyLine->setStock($product->getStock() + $product->getReserved());
                        $historyLine->save();
                    }
                }
                //set current date for date rdy order and save order
                $date = getdate();
                $day = $date['mday'];
                $month = $date['mon'];
                $year = $date['year'];
                $today = $year.'-'.$month.'-'.$day;

                $order->setDateReady($today);
                $order->save();
            }
            
            $this->redirect('sales_index_orders');
        }
    }   
    
    protected function processFormProduct(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $product = $form->save();
            $prodid = $product->getId();
       
            if (isset($_SESSION['partlist'])){
                $i = 0;
                ProductlineTable::deleteLine($prodid); //Remove productlines of the same product
                while(isset($_SESSION['partlist'][$i])){  
                    $productline = new Productline();
                    $productline->setProductId($prodid);
                    $partid = $_SESSION['partlist'][$i]['id'];
                    $productline->setPartId($partid);
                    $amount = $_SESSION['partlist'][$i]['amount'];
                    $productline->setAmount($amount);
                    $i++;
                    $productline->save();
                } 
            }
            unset($_SESSION['partlist']);
            
            $this->redirect('sales_index_pnp');
        }
    }
    
    protected function processFormProductEdit(sfWebRequest $request, sfForm $form){
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $product = $form->save();
            $prodid = $product->getId();
            
            if (isset($_SESSION['partlist'])){
                $i = 0;
                ProductlineTable::deleteLine($prodid); //Remove productlines of the same product
                while(isset($_SESSION['partlist'][$i])){  
                    $productline = new Productline();
                    $productline->setProductId($prodid);
                    $partid = $_SESSION['partlist'][$i]['id'];
                    $productline->setPartId($partid);
                    $amount = $_SESSION['partlist'][$i]['amount'];
                    $productline->setAmount($amount);
                    $i++;
                    $productline->save();
                } 
            }
            unset($_SESSION['partlist']);
            
            $this->redirect('sales_index_pnp');
        }
    }
    
    protected function processFormPart(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $part = $form->save();

            $this->redirect('sales_index_pnp');
        }
    }
    
    protected function processFormPartEdit(sfWebRequest $request, sfForm $form){
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $part = $form->save();

            $this->redirect('sales_index_pnp');
        }
    }
    
    public function executeFilterContacts(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'contacts';
        $this->showIndicator = 'index';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);

        //display the results with the Symfony pager object.
        $this->filter = new ContactFormFilter;
        $this->filter->bind($request->getParameter($this->filter->getName()));
        $this->pagerContacts = new sfDoctrinePager('Contact', sfConfig::get('app_max_items_on_page'));
        $this->pagerContacts->setQuery($this->filter->getQuery());
        $this->pagerContacts->setPage($request->getParameter('pagecontact', 1));
        $this->pagerContacts->init();

        //refer back to the index template
        $this->setTemplate('index');
    }
    
    public function executeFilterOrders(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'orders';
        $this->showIndicator = 'index';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);

        //display the results with the Symfony pager object.
        $this->filter = new _OrderFormFilter;
        $this->filter->bind($request->getParameter($this->filter->getName()));
        $this->pagerOrders = new sfDoctrinePager('_Order', sfConfig::get('app_max_items_on_page'));
        $this->pagerOrders->setQuery($this->filter->getQuery());
        $this->pagerOrders->setPage($request->getParameter('pageorder', 1));
        $this->pagerOrders->init();

        //refer back to the index template
        $this->setTemplate('index');
    }
    
    public function executeFilterPnP(sfWebRequest $request) {
        //Required variables for index template
        $this->tab = 'pnp';
        $this->showIndicator = 'index';
        $this->processBooleans($this->tab, $this->showIndicator);
        $this->processVariables($request, $this->tab);

        //display the results with the Symfony pager object.
        $this->filterParts = new PartFormFilter;
        $this->filterParts->bind($request->getParameter($this->filterParts->getName()));
        $this->pagerParts = new sfDoctrinePager('Part', sfConfig::get('app_max_items_on_page'));
        $this->pagerParts->setQuery($this->filterParts->getQuery());
        $this->pagerParts->setPage($request->getParameter('pagepart', 1));
        $this->pagerParts->init();

         //display the results with the Symfony pager object.
        $this->filterProducts = new ProductFormFilter;
        $this->filterProducts->bind($request->getParameter($this->filterProducts->getName()));
        $this->pagerProducts = new sfDoctrinePager('Product', sfConfig::get('app_max_items_on_page'));
        $this->pagerProducts->setQuery($this->filterProducts->getQuery());
        $this->pagerProducts->setPage($request->getParameter('pageproduct', 1));
        $this->pagerProducts->init();
        
        //refer back to the index template
        $this->setTemplate('index');
    }
      
    public function executePrintOrder(sfWebRequest $request) {
        $this->order = $this->getRoute()->getObject();
        $this->tab = 'print';
        $this->setTemplate('new');
    }
    
    /**
     * Save all the variables and objects needed for the documents of this order
     * @param sfWebRequest $request 
     */
    public function executeShowDocument(sfWebRequest $request) {
        $this->forward404Unless($order = _OrderTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object order does not exist (%s).', $request->getParameter('id')));
        $this->contact = ContactTable::getInstance()->findOneBy('id', $order->getContactId());
        $this->company = CompanyTable::getInstance()->findOneBy('id', 1);
        $this->items = PPView::findbyOrder($order);
        $this->materials = MaterialsUsedView::findbyOrder($order);
        $this->order = $order;
        $this->version = 'showDocuments';
        $this->setLayout(false);
        $this->setTemplate('show');
    }   
       
    /**
     * Give booleans that are used in the index template to decide what needs to be shown the correct values.
     * @param $tab is the page of the website,
     *             i.e. contacts, orders, products&parts, etc.
     * @param $showIndicator indicates what part of the page needs to be shown.
     * @return array of booleans
     */
    protected function processBooleans($tab, $showIndicator) {
        if ($tab == 'contacts') {
            if ($showIndicator == 'index') {
                $this->showContact = false;
                $this->showOrdersContact = false;
                $this->showNote = false;
            }
            if ($showIndicator == 'showContact') {
                $this->showContact = true;
                $this->showOrdersContact = false;
                $this->showNote = false;
            }
            if ($showIndicator == 'showOrdersContact') {
                $this->showContact = false;
                $this->showOrdersContact = true;
                $this->showNote = false;
            }
            if ($showIndicator == 'showNote') {
                $this->showContact = false;
                $this->showOrdersContact = false;
                $this->showNote = true;
            }
            return array($this->showContact, $this->showOrdersContact, $this->showNote);
        }
        if ($tab == 'orders') {
            if ($showIndicator == 'index') {
                $this->showOrder = false;
                $this->showMaterialsOrder = false;
            }
            if ($showIndicator == 'showOrder') {
                $this->showOrder = true;
                $this->showMaterialsOrder = false;
            }
            if ($showIndicator == 'showMaterialsOrder') {
                $this->showOrder = false;
                $this->showMaterialsOrder = true;
            }
            return array($this->showOrder, $this->showMaterialsOrder);
        }
        if ($tab == 'pnp' || $tab == 'products' || $tab == 'parts') {
            
        }

    }

    /**
     * Give all the variables needed in index a value.
     * @param sfWebRequest $request
     * @return array of variables
     */
    protected function processVariables(sfWebRequest $request, $tab) {
        //Contacts
        $this->pagerContacts = new sfDoctrinePager('Contact', sfConfig::get('app_max_items_on_page'));
        $this->pagerContacts->setPage($request->getParameter('pagecontact', 1));
        $this->pagerContacts->init();

        //Orders
        $this->pagerOrders = new sfDoctrinePager('_Order', sfConfig::get('app_max_items_on_page'));
        $this->pagerOrders->setQuery(_OrderTable::findAllDescQuery());
        $this->pagerOrders->setPage($request->getParameter('pageorder', 1));
        $this->pagerOrders->init();

        //Products
        $this->pagerProducts = new sfDoctrinePager('Product', sfConfig::get('app_max_items_on_page'));
        $this->pagerProducts->setPage($request->getParameter('pageproduct', 1));
        $this->pagerProducts->init();

        //Parts
        $this->pagerParts = new sfDoctrinePager('Part', sfConfig::get('app_max_items_on_page'));
        $this->pagerParts->setPage($request->getParameter('pagepart', 1));
        $this->pagerParts->init();
            
        $this->pagerOrdersContact = new sfDoctrinePager('_Order', sfConfig::get('app_max_orders_contact_on_page'));
        $this->pagerItems = new sfDoctrinePager('PP', sfConfig::get('app_max_orders_contact_on_page'));
       
        $this->order = '';
        $this->contact = '';
        $this->ordersContact = '';
        
        if($tab == 'contacts')
        $this->filter = new ContactFormFilter();
        if($tab == 'orders')
        $this->filter = new _OrderFormFilter();
        if ($tab == 'pnp' ||  $tab == 'parts' || $tab == 'products'){
        $this->filterParts = new PartFormFilter();
        $this->filterProducts = new ProductFormFilter();    
        }

        return array($this->contact, $this->ordersContact, $this->pagerContacts, $this->pagerOrders, $this->pagerProducts, $this->pagerParts, $this->filter);
    }
    
    /**
     * Create a new reservedline for either a material or product and save to the database
     * @param type $version
     * @param type $orderId
     * @param type $itemId
     * @param type $reserved
     * @param type $required 
     */
    protected function createReservedLine($version, $orderId, $itemId, $reserved, $required){
        if($version == 'product'){
            $reservedline = new Reservedline();
            $reservedline->setOrderId($orderId);
            $reservedline->setProductId($itemId);
            $reservedline->setReserved($reserved);
            $reservedline->setRequired($required);
            $reservedline->setProduction(0);
            $reservedline->save();      
        }
        if($version == 'material'){
            $reservedline = new Reservedline();
            $reservedline->setOrderId($orderId);
            $reservedline->setMaterialId($itemId);
            $reservedline->setReserved($reserved);
            $reservedline->setRequired($required);
            $reservedline->setProduction(0);
            $reservedline->save();     
        }
    }
}
